package com.daffodil.medium.config;

import java.time.Duration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.daffodil.medium.properties.AliyunProperties;
import com.daffodil.medium.properties.MediumProperties;

import darabonba.core.client.ClientOverrideConfiguration;

/**
 * 
 * @author yweijian
 * @date 2022年11月11日
 * @version 1.0
 * @description
 */
@Component
@Configuration
@ConditionalOnProperty(name = "daffodil.medium.sender", havingValue = "aliyun")
public class AliyunSmsClientConfig {

	@Autowired
	private MediumProperties mediumProperties;
	
	@Bean
	@ConditionalOnMissingBean
	public AsyncClient asyncClient() {
		AliyunProperties properties = mediumProperties.getAliyun();
		Credential credential = Credential.builder()
				.accessKeyId(properties.getAccessKeyId())
				.accessKeySecret(properties.getAccessKeySecret())
				.build();
		
		StaticCredentialProvider provider = StaticCredentialProvider.create(credential);
		
		ClientOverrideConfiguration configuration = ClientOverrideConfiguration.create()
				.setEndpointOverride(properties.getEndpoint())
				.setConnectTimeout(Duration.ofSeconds(30));
		
		AsyncClient client = AsyncClient.builder()
                .region(properties.getRegion())
                .credentialsProvider(provider)
                .overrideConfiguration(configuration)
                .build();
		
		return client;
	}
}
